#include "widget.h"
#include "ui_widget.h"



// 回调函数：当连接成功时触发
void on_connect(struct mosquitto *mosq, void *userdata, int result) {
    if (result == 0) {
        qDebug() << "Connected to broker!";
        // 订阅主题
        mosquitto_subscribe(mosq, NULL, "mqtttest0413", 0);
    } else {
        qDebug() << "Connection failed!";
    }
}

// 回调函数：当接收到消息时触发
void on_message(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *message) {
    qDebug() << "Received message:" << QString::fromUtf8((char *)message->payload) << "on topic:" << message->topic;
#if 1
    char tmpArr[5] = {0};
    strncpy(tmpArr,(char*)message->payload+2,4);
    QString tmpStr(tmpArr);
#endif
    Widget *t = (Widget*)userdata;
    t->lineedit1->setText(tmpStr);


}
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    label1 = new QLabel("light");
    label2 = new QLabel("smoke");
    lineedit1 = new QLineEdit();
    lineedit2 = new QLineEdit();
    button1 = new QPushButton("fan on");
    button2 = new QPushButton("fan off");
    mylayout = new QGridLayout();
    mylayout->addWidget(label1,0,0);
    mylayout->addWidget(lineedit1,0,1);
    mylayout->addWidget(label2,1,0);
    mylayout->addWidget(lineedit2,1,1);

    mylayout->addWidget(button1,2,0);
    mylayout->addWidget(button2,2,1);

    mylayout->setSpacing(30);
    mylayout->setMargin(100);

    this->setLayout(mylayout);
    connect(button1,&QPushButton::clicked, this,&Widget::on_button1_clicked);
    connect(button2,&QPushButton::clicked, this,&Widget::on_button2_clicked);


    mosquitto_lib_init();
    // 创建 Mosquitto 客户端实例
   mosq = mosquitto_new("6dbb6ca4f3364454adfed61c79acdf24", true, this);
    if (!mosq) {
        qCritical() << "Failed to create Mosquitto client!";
        //return -1;
    }

    // 设置回调函数
    mosquitto_connect_callback_set(mosq, on_connect);
    mosquitto_message_callback_set(mosq, on_message);

    // 连接到 MQTT 代理
    int rc = mosquitto_connect(mosq, "bemfa.com", 9501, 60);
    if (rc != MOSQ_ERR_SUCCESS) {
        qCritical() << "Failed to connect to broker!";
        mosquitto_destroy(mosq);
        mosquitto_lib_cleanup();
        //return -1;
    }

    // 启动网络循环
    mosquitto_loop_start(mosq);

}

Widget::~Widget()
{
    delete ui;
    mosquitto_loop_stop(mosq, true);
    mosquitto_destroy(mosq);
    mosquitto_lib_cleanup();
}


void Widget::on_button1_clicked()
{
           const char *msg = "9#1";
    mosquitto_publish(mosq, NULL, "mqtttest0413", strlen(msg), msg, 0, false);
}

void Widget::on_button2_clicked()
{
           const char *msg = "9#0";
    mosquitto_publish(mosq, NULL, "mqtttest0413", strlen(msg), msg, 0, false);
}
